# -*- coding: utf-8 -*-
"""
Copyright (c) 2020, Nimblex Co .,Ltd.

Created on 2020-12-11 11:28
"""
import sys

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import sqlalchemy.engine.url as url


Base = declarative_base()


class Counter(Base):
    __tablename__ = 'counters'

    id = Column(Integer, primary_key=True)
    counter = Column(Integer)


engine = None


def init_db_engine(host, port, dbname, user, passwd, ssl_ca, ssl_cert, ssl_key):
    global engine
    uri = url.URL(
        drivername="postgresql",
        host=host,
        port=port,
        username=user,
        password=passwd,
        database=dbname,
    )

    ssl_args = {
        "sslmode": "verify-full",
        "sslrootcert": ssl_ca,
        "sslcert": ssl_cert,
        "sslkey": ssl_key
    }
    engine = create_engine(uri, connect_args=ssl_args, encoding='utf-8', echo=False,
                           pool_size=100, pool_recycle=3600, pool_pre_ping=True)


def get_session():
    global engine
    SessionCls = sessionmaker(bind=engine)
    return SessionCls()


def main():
    host = sys.argv[1]
    port = int(sys.argv[2])

    init_db_engine(host, port, 'test', 'test', 'test', './root.crt', './memfiredb.crt', './memfiredb.key')
    Base.metadata.create_all(engine)

    session = get_session()
    session.execute('delete from counters')
    cnt = Counter(counter=1)
    session.add(cnt)
    session.commit()
    session.close()


if __name__ == '__main__':
    main()
